import 'package:date_format/date_format.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:my_app/common/common.dart';
import 'package:my_app/global/global.dart';
import 'package:my_app/qr_detail/qr_detail.dart';
import 'package:my_app/service/api/api.dart';

class QrListMenu extends StatefulWidget {
  QrListMenu({Key? key}) : super(key: key);

  @override
  State<QrListMenu> createState() => _QrListMenuState();
}

class _QrListMenuState extends State<QrListMenu> {
  // button 文字样式
  TextStyle _buttonTextStyle = TextStyle(
    fontSize: 10.0,
    color: Colors.white,
  );
  // button 样式
  ButtonStyle _buttonStyle = TextButton.styleFrom(
    backgroundColor: Color(Common.muji),
    padding: EdgeInsets.all(5),
  );

  DateTime _selectedDate = DateTime.now(); //当前选中的日期
  // TimeOfDay _selectedTime = TimeOfDay.now(); //当前选中的时间
  //label 字体大小
  TextStyle textStyle = TextStyle(fontSize: 10);
  // list 内容文字大小
  TextStyle listStyle = TextStyle(fontSize: 11);
  // label 文字对齐方式
  TextAlign textStyleAlign = TextAlign.end;
  // label 和 input 距离
  Widget widgetWidth = SizedBox(
    width: 10,
  );
  List listData = [];
  double paddingLeft = 45.0;
  double itemWidth = 100.0;
  // listView 滚动
  ScrollController _scrollController = ScrollController();
  String _qrCode = ""; // 二维码
  String _goodsCode = ""; // 商品条码
  String productionDate = ""; // 生产日期
  var _status = 0; // 状态选择值
  String validityDate = ""; // 效期
  String goodsName = ""; // 商品名称
  String startNum = '1'; // 开始数
  String endNum = '200'; // 结束数
  TextEditingController _qrcontroller = new TextEditingController();
  TextEditingController _goodscontroller = new TextEditingController();
  TextEditingController _validityDatecontroller = new TextEditingController();
  TextEditingController _goodNamecontroller = new TextEditingController();
  int _validityDateStatus = 0;
  @override
  initState() {
    getListData("");
    super.initState();
    // Map userinfo = {"userName":"张三","age":20};
  }

  double getFromWidth() {
    MediaQueryData mq;
    mq = MediaQuery.of(context);
    // 设备宽度
    double deviceWidth = mq.size.width;
    double width = 210;
    if (deviceWidth > 360) {
      width = 200;
    } else {
      width = mq.size.width - 80;
    }
    return width;
  }

  double getWidth() {
    MediaQueryData mq;
    mq = MediaQuery.of(context);
    // 设备宽度
    double deviceWidth = mq.size.width;
    double width = 210; // 列表内容大小
    if (deviceWidth > 360) {
      width = 180;
    } else {
      width = 133;
    }
    return width;
  }

  double getfontSize() {
    MediaQueryData mq;
    mq = MediaQuery.of(context);
    // 设备宽度
    double deviceWidth = mq.size.width;
    double fontSize = 11; // 列表内容大小
    if (deviceWidth > 360) {
      fontSize = 11;
    } else {
      fontSize = 8;
    }
    return fontSize;
  }

  void getListData(status) async {
    print("EasyLoading");
    EasyLoading.show(status: 'loading...', dismissOnTap: true);
    var prdDate;
    if (productionDate == "") {
      prdDate = "";
    } else {
      // prdDate = _selectedDate.toString().substring(0, 19);
      prdDate = productionDate;
    }
    if (_status == 0) {
      status = "";
    }
    var unit = '';
    if (validityDate != '') {
      if (_validityDateStatus == 0) {
        unit = '天';
      } else if (_validityDateStatus == 1) {
        unit = '个月';
      } else if (_validityDateStatus == 2) {
        unit = '年';
      }
    }

    var data = await ApiService.allQrListData(
      startNum,
      endNum,
      GlobalData.staffID,
      _qrCode,
      _goodsCode,
      validityDate + unit,
      prdDate,
      goodsName,
      status,
    );
    // print(
    //     "_________________________________________listData__________________________");
    // print(data);
    EasyLoading.dismiss();
    try {
      if (data != null) {
        print("qrlistmenu_83");
        print(data.length);
        if (data.length == 1 && data[0]["ERROR_MSG"] != null) {
          Common.showTost(data.toString());
          return;
        }
        for (int i = 0; i < data.length; i++) {
          if (data[i]["SHELF_LIFE"] == "") {
            data[i]["SHELF_LIFE"] = "效期异常";
          }
        }
        listData = data;
        // print("_________________________listData");
        // print(listData);
        setState(() {
          listData = data;
        });
      }
    } catch (err) {
      Future.delayed(Duration(milliseconds: 5000), () {
        Common.showTost(err.toString());
      });
    }
  }

  // 渲染list widget
  List<Widget> _getListData() {
    List<Widget> listdd = [];

    for (var i = 0; i < this.listData.length; i++) {
      listdd.add(
        Container(
          height: 40,
          child: InkWell(
            onTap: () {
              print(listData[i]["ITEM_ID"]);
              Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                return QrDetail(
                  qrCode: this.listData[i]["QR_ID"],
                  isEdit: this.listData[i]["QR_FLG"],
                );
              })).then((value) => {
                    print(value),
                    _qrcontroller.text = "",
                    _goodscontroller.text = "",
                    _validityDatecontroller.text = "",
                    _goodNamecontroller.text = "",
                    setState(() {
                      productionDate = "";
                      _qrCode = "";
                      goodsName = "";
                      _goodsCode = "";
                      _status = 0;
                      _validityDateStatus = 0;
                    }),
                    getListData(''),
                  });
            },
            child: Row(
              // textBaseline: TextBaseline.ideographic,
              // mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Container(
                  width: getWidth(),
                  child: Container(
                    height: 14,
                    decoration: BoxDecoration(
                      border: Border(
                        bottom: BorderSide(width: 0.3, color: Colors.black),
                      ),
                    ),
                    child: Text(
                      this.listData[i]["QR_ID"],
                      style: TextStyle(fontSize: getfontSize()),
                    ),
                  ),
                ),
                Container(
                  width: getWidth() - 60,
                  child: Container(
                    height: 14,
                    decoration: BoxDecoration(
                      border: Border(
                        bottom: BorderSide(width: 0.3, color: Colors.black),
                      ),
                    ),
                    child: Text(
                      this.listData[i]["ITEM_ID"],
                      style: TextStyle(fontSize: getfontSize()),
                    ),
                  ),
                ),
                Container(
                  width: getWidth() - 70,
                  child: Container(
                    height: 14,
                    decoration: BoxDecoration(
                      border: Border(
                        bottom: BorderSide(width: 0.3, color: Colors.black),
                      ),
                    ),
                    child: Text(
                      this.listData[i]["END_DT"],
                      // "2022-12-30",
                      style: TextStyle(fontSize: getfontSize()),
                    ),
                  ),
                ),
                Container(
                  width: getWidth() - 80,
                  child: Container(
                    height: 14,
                    decoration: BoxDecoration(
                      border: Border(
                        bottom: BorderSide(width: 0.3, color: Colors.black),
                      ),
                    ),
                    width: itemWidth,
                    child: Text(
                      this.listData[i]["SHELF_LIFE"] +
                          this.listData[i]["SHELF_LIFE_UNIT"],
                      // "2022-12-30",
                      style: TextStyle(fontSize: getfontSize()),
                    ),
                  ),
                ),
                Expanded(
                  flex: 1,
                  child: Container(
                    height: 14,
                    decoration: BoxDecoration(
                      border: Border(
                        bottom: BorderSide(width: 0.3, color: Colors.black),
                      ),
                    ),
                    child: Text(
                      this.listData[i]["QR_FLG"],
                      style: TextStyle(fontSize: getfontSize()),
                    ),
                  ),
                ),
                SizedBox(width: 10),
                // Text("______"),
                // Text(this.listData[i]["goodsCode"]),
              ],
            ),
          ),
        ),
      );
    }
    return listdd;
  }

  @override
  Widget build(BuildContext context) {
    //调起日期选择器
    _showDatePicker() {
      //获取异步方法里面的值的第一种方式：then
      showDatePicker(
        //如下四个参数为必填参数
        context: context,
        cancelText: "取消",
        confirmText: "确认",
        locale: Locale('zh'),
        initialDate: _selectedDate, //选中的日期
        firstDate: DateTime(1980), //日期选择器上可选择的最早日期
        lastDate: DateTime(2100), //日期选择器上可选择的最晚日期
      ).then((selectedValue) {
        setState(() {
          //将选中的值传递出来
          this._selectedDate = selectedValue!;
          productionDate =
              formatDate(this._selectedDate, [yyyy, "-", mm, "-", "dd"]);
          // this._selectedDate,
          // [HH, ':', nn, ':', ss]);
        });
      });
    }

    //调起时间选择器
    // _showTimePicker() async {
    //   // 获取异步方法里面的值的第二种方式：async+await
    //   //await的作用是等待异步方法showDatePicker执行完毕之后获取返回值
    //   var result = await showTimePicker(
    //     context: context,
    //     initialTime: _selectedTime, //选中的时间
    //   );
    //   //将选中的值传递出来
    //   setState(() {
    //     this._selectedTime = result!;
    //   });
    // }

    return Scaffold(
      appBar: AppBar(
        title: Text('二维码赋码详情'),
        centerTitle: true,
        backgroundColor: Color(Common.muji),
        leading: IconButton(
          tooltip: '返回',
          icon: const Icon(Icons.arrow_back),
          onPressed: () {
            Navigator.of(context).pop();
          },
        ),
      ),
      floatingActionButton: FloatingActionButton(
        backgroundColor: Color(Common.muji),
        child: Icon(
          Icons.arrow_upward,
          color: Colors.white,
          size: 40,
        ),
        onPressed: () {
          _scrollController.jumpTo(0.0);
        },
      ),
      body: Padding(
        padding: EdgeInsets.fromLTRB(10, 30, 0, 0),
        child: Column(
          children: [
            Wrap(
              spacing: 2, //主轴上子控件的间距
              runSpacing: 5, //交叉轴上子控件之间的间距
              children: [
                Container(
                  height: 30,
                  // decoration: new BoxDecoration(
                  //   color: Colors.grey,
                  // ),
                  width: 50,
                  child: Text(
                    "二维码:",
                    style: textStyle,
                    textAlign: textStyleAlign,
                  ),
                ),
                Container(
                  height: 30,
                  width: getFromWidth(),
                  child: TextField(
                    onChanged: (value) {
                      _qrCode = value;
                      print(value);
                    },
                    controller: _qrcontroller,
                    keyboardType: TextInputType.emailAddress,
                    onSubmitted: (value) {
                      // Uri u = Uri.parse(value);
                      // value = u.queryParameters['qrCode'].toString();
                      value = value.split("=")[1];
                      _qrcontroller.text = value;
                      // _qrfocusNode.unfocus();
                      // FocusScope.of(context).requestFocus(_goodsfocusNode);
                      // 保存qr码
                      setState(() {
                        _qrCode = value;
                      });
                    },
                    style: TextStyle(fontSize: 8),
                    decoration: InputDecoration(
                      border: OutlineInputBorder(
                        borderSide: BorderSide(color: Colors.black, width: 2.0),
                      ),
                      focusedBorder: Common.focusedBorder,
                    ),
                  ),
                ),
                Container(
                  width: 50,
                  child: Text(
                    "商品条码:",
                    style: textStyle,
                    textAlign: textStyleAlign,
                  ),
                ),
                Container(
                  height: 30,
                  width: getFromWidth(),
                  child: TextField(
                    onChanged: (value) {
                      _goodsCode = value;
                    },
                    controller: _goodscontroller,
                    style: TextStyle(fontSize: 10),
                    decoration: InputDecoration(
                      border: OutlineInputBorder(
                        borderSide: BorderSide(color: Colors.black, width: 2.0),
                      ),
                      focusedBorder: Common.focusedBorder,
                    ),
                  ),
                ),

                // Container(
                //   width: 20,
                //   child: Text(
                //     "(天)",
                //     style: textStyle,
                //     textAlign: TextAlign.start,
                //   ),
                // ),
              ],
            ),
            SizedBox(height: 10),
            Wrap(
              spacing: 2, //主轴上子控件的间距
              runSpacing: 5, //交叉轴上子控件之间的间距
              children: [
                Container(
                  width: 50,
                  child: Text(
                    "生产日期:",
                    style: textStyle,
                    textAlign: textStyleAlign,
                  ),
                ),
                Container(
                  height: 30,
                  width: getFromWidth(),
                  decoration: BoxDecoration(
                    border: Border.all(color: Colors.black38, width: 1),
                    borderRadius: BorderRadius.vertical(
                      top: Radius.elliptical(4, 4),
                      bottom: Radius.elliptical(4, 4),
                    ),
                  ),
                  child: InkWell(
                    onTap: () => {
                      _showDatePicker(),
                      print(_selectedDate),
                    },
                    child: Row(
                      children: <Widget>[
                        Container(
                          width: getFromWidth() - 25,
                          child: Text(productionDate),
                        ),
                        // SizedBox(
                        //   width: 10,
                        // ),
                        Icon(
                          Icons.arrow_drop_down,
                          size: 20,
                        )
                      ],
                    ),
                  ),
                ),
                Container(
                  width: 50,
                  child: Text(
                    "状态:",
                    style: textStyle,
                    textAlign: textStyleAlign,
                  ),
                ),
                Container(
                  height: 30,
                  width: getFromWidth(),
                  decoration: BoxDecoration(
                    border: Border.all(color: Colors.black38, width: 1),
                    borderRadius: BorderRadius.vertical(
                      top: Radius.elliptical(4, 4),
                      bottom: Radius.elliptical(4, 4),
                    ),
                  ),
                  child: DropdownButton(
                      value: _status,
                      icon: Icon(Icons.arrow_drop_down),
                      iconSize: 20,
                      iconEnabledColor: Colors.black.withOpacity(0.7),
                      hint: Text('请选择'),
                      style: TextStyle(color: Colors.black, fontSize: 12),
                      isExpanded: true,
                      underline: Container(color: Colors.white),
                      items: [
                        DropdownMenuItem(
                            child: Row(children: <Widget>[
                              Text('全部 '),
                              SizedBox(width: 10),
                              // Icon(Icons.ac_unit)
                            ]),
                            value: 0),
                        DropdownMenuItem(
                            child: Row(children: <Widget>[
                              Text('已赋码 '),
                              SizedBox(width: 10),
                              // Icon(Icons.ac_unit)
                            ]),
                            value: 1),
                        DropdownMenuItem(
                            child: Row(children: <Widget>[
                              Text('未赋码'),
                              SizedBox(width: 10),
                              // Icon(Icons.ac_unit)
                            ]),
                            value: 2),
                      ],
                      onChanged: (value) {
                        setState(() => _status = value as int);

                        print(value);
                      }),
                ),
              ],
            ),
            SizedBox(height: 10),
            Wrap(
              spacing: 2, //主轴上子控件的间距
              runSpacing: 5, //交叉轴上子控件之间的间距
              children: [
                Container(
                  width: 50,
                  child: Text(
                    "商品名称:",
                    style: textStyle,
                    textAlign: textStyleAlign,
                  ),
                ),
                Container(
                  height: 30,
                  width: getFromWidth(),
                  // color: Colors.amber,
                  // decoration: sty(

                  // ),
                  child: TextField(
                    onChanged: (value) {
                      goodsName = value;
                      print(value);
                    },
                    style: TextStyle(fontSize: 10),
                    controller: _goodNamecontroller,
                    decoration: InputDecoration(
                      border: OutlineInputBorder(
                        borderSide: BorderSide(color: Colors.black, width: 2.0),
                      ),
                      focusedBorder: Common.focusedBorder,
                    ),
                  ),
                ),
                Container(
                  width: 50,
                  child: Text(
                    "效期:",
                    style: textStyle,
                    textAlign: textStyleAlign,
                  ),
                ),
                Container(
                  height: 30,
                  width: getFromWidth() - 85,
                  child: TextField(
                    onChanged: (value) {
                      validityDate = value;
                      print(value);
                    },
                    // maxLength: 3,
                    keyboardType: TextInputType.number,
                    controller: _validityDatecontroller,
                    style: TextStyle(fontSize: 10),
                    decoration: InputDecoration(
                      border: OutlineInputBorder(
                        borderSide: BorderSide(color: Colors.black, width: 2.0),
                      ),
                      focusedBorder: Common.focusedBorder,
                    ),
                  ),
                ),
                Container(
                  height: 30,
                  width: 85,
                  child: Container(
                    height: 30,
                    width: 85,
                    decoration: BoxDecoration(
                      border: Border.all(color: Colors.black38, width: 1),
                      borderRadius: BorderRadius.vertical(
                        top: Radius.elliptical(4, 4),
                        bottom: Radius.elliptical(4, 4),
                      ),
                    ),
                    child: DropdownButton(
                        value: _validityDateStatus,
                        icon: Icon(Icons.arrow_drop_down),
                        iconSize: 20,
                        iconEnabledColor: Colors.black.withOpacity(0.7),
                        hint: Text('请选择'),
                        style: TextStyle(color: Colors.black, fontSize: 12),
                        isExpanded: true,
                        underline: Container(color: Colors.white),
                        items: [
                          DropdownMenuItem(
                              child: Row(children: <Widget>[
                                Text('天 '),
                                SizedBox(width: 10),
                                // Icon(Icons.ac_unit)
                              ]),
                              value: 0),
                          DropdownMenuItem(
                              child: Row(children: <Widget>[
                                Text('个月 '),
                                SizedBox(width: 10),
                                // Icon(Icons.ac_unit)
                              ]),
                              value: 1),
                          DropdownMenuItem(
                              child: Row(children: <Widget>[
                                Text('年'),
                                SizedBox(width: 10),
                                // Icon(Icons.ac_unit)
                              ]),
                              value: 2),
                        ],
                        onChanged: (value) {
                          setState(() => _validityDateStatus = value as int);
                          print(value);
                        }),
                  ),
                ),
              ],
            ),
            SizedBox(height: 10),
            Row(
              children: [
                Container(
                  width: 60,
                  height: 30,
                  child: TextButton(
                    style: _buttonStyle,
                    child: Text(
                      "查询",
                      style: _buttonTextStyle,
                    ),
                    onPressed: () => {
                      if (_status != null)
                        {
                          getListData(_status.toString()),
                          print('$_qrCode-$_goodsCode-$_status')
                        }
                      else
                        {
                          getListData(""),
                        }
                    },
                  ),
                ),
              ],
            ),
            SizedBox(height: 20),
            Container(
              height: 20,
              child: Row(
                // textBaseline: TextBaseline.ideographic,
                // mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                // mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Container(
                    width: getWidth(),
                    child: Row(
                      children: [
                        Text(
                          "二维码",
                          style: TextStyle(fontSize: getfontSize()),
                        ),
                      ],
                    ),
                  ),
                  Container(
                    width: getWidth() - 60,
                    child: Row(
                      children: [
                        Text(
                          "商品条码",
                          style: TextStyle(fontSize: getfontSize()),
                        ),
                      ],
                    ),
                  ),
                  Container(
                    width: getWidth() - 70,
                    child: Row(
                      children: [
                        Text(
                          "到期日期",
                          style: TextStyle(fontSize: getfontSize()),
                        ),
                      ],
                    ),
                  ),
                  Container(
                    width: getWidth() - 80,
                    child: Row(
                      children: [
                        Text(
                          "有效期",
                          style: TextStyle(fontSize: getfontSize()),
                        ),
                      ],
                    ),
                  ),
                  Expanded(
                    flex: 1,
                    child: Text(
                      "状态",
                      style: TextStyle(fontSize: getfontSize()),
                    ),
                  ),
                ],
              ),
            ),
            Expanded(
              child: Container(
                // color: Colors.red,
                child: ListView(
                  controller: _scrollController,
                  children: this._getListData(),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
